package com.lixianhe.onlineexam.controller;

import com.lixianhe.onlineexam.pojo.Admin;
import com.lixianhe.onlineexam.pojo.Student;
import com.lixianhe.onlineexam.pojo.Teacher;

import com.lixianhe.onlineexam.pojo.Login;
import com.lixianhe.onlineexam.service.LoginService;
import com.lixianhe.onlineexam.util.ApiResultHandler;
import com.lixianhe.onlineexam.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    public R login(@RequestBody Login login, HttpServletRequest request) {
        Integer username = login.getUsername();
        String password = login.getPassword();
        Admin adminRes = loginService.adminLogin(username, password);
        if (adminRes != null) {
            request.getSession().setAttribute("admin", "admin");
            return ApiResultHandler.buildApiResult(200, "请求成功", adminRes);
        }
        Teacher teacherRes = loginService.teacherLogin(username, password);
        if (teacherRes != null) {
            request.getSession().setAttribute("teacher", "teacher");
            return ApiResultHandler.buildApiResult(200, "请求成功", teacherRes);
        }
        Student studentRes = loginService.studentLogin(username, password);
        if (studentRes != null) {
            request.getSession().setAttribute("student", "student");
            return ApiResultHandler.buildApiResult(200, "请求成功", studentRes);
        }
        return ApiResultHandler.buildApiResult(400, "请求失败", null);
    }

}
